<template>
  <div class="table-wrapper table-item-h">
    <div class="table-header">
      <div class="header-right">
        <el-button
            type="primary"
            @click="handleExport"
        >
          <el-icon>
            <Download/>
          </el-icon>
          导出
        </el-button>
      </div>
    </div>

    <el-table
        ref="tableRef"
        v-loading="loading"
        :data="data"
        row-key="id"
        class="main-table"
        :fit="true"
        @sort-change="$emit('sort-change', $event)"
        @expand-change="handleExpandChange"
    >
      <el-table-column type="expand" fixed>
        <template #default="props">
          <course-table
              :data="props.row.children"
              @sort-change="$emit('sort-change', $event)"
              @expand-change="(row, expanded) => handleCourseExpand(row, expanded, props.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
          v-for="(col, index) in columns"
          :key="col.prop || col.type"
          v-bind="col"
          :fixed="index < 1"
      />
    </el-table>
  </div>
</template>

<script setup>
import {ElMessage, ElMessageBox, ElLoading} from 'element-plus'
import {Download} from '@element-plus/icons-vue'
import {exportStatistics} from '@/api/statices.js'
import {mainTableColumns} from '../const'
import CourseTable from './CourseTable.vue'
import {getFormatDate} from '../../../../../utils/dateFormat'

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  columns: {
    type: Array,
    default: () => mainTableColumns
  },
  queryParams: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['sort-change', 'expand-change', 'course-expand'])

// 处理主表格展开
const handleExpandChange = (row, expanded) => {
  emit('expand-change', row, expanded)
}

// 处理课程表格展开
const handleCourseExpand = (expandedRow, expanded, parentRow) => {
  emit('course-expand', {expandedRow, expanded, parentRow})
}

// 处理导出
const handleExport = async () => {
  try {
    // 二次确认
    await ElMessageBox.confirm('确认要导出数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 显示加载中
    const loading = ElLoading.service({
      lock: true,
      text: '正在导出...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 构建导出参数
      const exportParams = {
        goodsId: props.queryParams.goodsId || '',
        buyerMobile: props.queryParams.buyerMobile || '',
        buyerName: props.queryParams.buyerName || '',
        createStartDate: props.queryParams.createStartDate || '',
        createEndDate: props.queryParams.createEndDate || ''
      }

      const response = await exportStatistics(exportParams)

      // 创建下载链接
      const blob = new Blob([response], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `学习统计${getFormatDate(new Date())}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败：', error)
      ElMessage.error('导出失败，请稍后重试')
    } finally {
      loading.close()
    }
  } catch (error) {
    // 用户取消导出，不做处理
    if (error !== 'cancel') {
      console.error('导出操作异常：', error)
      ElMessage.error('操作异常，请稍后重试')
    }
  }
}
</script>

<style scoped lang="scss">
// 引入公共样式
@import '@/assets/styles/common.scss';

.table-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  :deep(.el-table) {
    height: 100%;

    // 表头样式
    .el-table__header-wrapper {
      th {
        background-color: #F5F7FA !important;
        color: #606266;
        font-weight: 600;
        border-bottom: 1px solid #EBEEF5;
      }
    }

    // 表格行样式
    .el-table__row {
      border-bottom: 1px solid #EBEEF5;

      &:hover {
        background-color: #F5F7FA !important;
      }
    }

    // 单元格样式
    .el-table__cell {
      white-space: nowrap; // 直接使用样式而不是 @extend
      border: none !important;
      padding: 8px 0;
    }

    // 展开图标样式
    .el-table__expand-icon {
      color: #409EFF;
      font-size: 16px;
      transition: transform 0.2s ease-in-out;

      &--expanded {
        transform: rotate(90deg);
      }
    }

    // 展开行样式
    .el-table__expanded-cell {
      padding: 0 !important;

      .el-table {
        margin: 0 !important;
      }
    }

    // 滚动条样式
    .el-scrollbar__wrap {
      overflow-x: hidden !important;
    }

    // 固定列样式
    .el-table__fixed-header-wrapper {
      background-color: #F5F7FA;
    }

    // 移除表格边框
    &::before,
    &::after {
      display: none;
    }
  }
}

// 主表格样式
.main-table {
  flex: 1;
  min-height: 0;

  :deep(.el-table__body-wrapper) {
    overflow-y: auto !important;
  }
}

// 添加表格头部样式
.table-header {
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-bottom: 1px solid #EBEEF5;

  .header-right {
    display: flex;
    align-items: center;
    gap: 8px;


  }
}
</style>
